using System;
using Tools.Domain.Common.Repositories.Contracts;
using Web.App.Infrastructure.CrossCuttingConcerns.Attributes;
using Web.App.Infrastructure.Extensions;
using Web.App.Infrastructure.ObjectStore.Contracts;
using Webshop20.Application.Operations.Messages;
using Webshop20.Domain.Catalog.Core;

namespace Webshop20.Application.Operations.Services
{
    public interface IMergeCartsService : IService
    {
        [Transaction]
        new ISystemMessage Handle(ISystemMessage request);
    }

    public class MergeCartsService : IMergeCartsService
    {
        private IRepository<Visitor> visitors;
        private IObjectStoreRepository objectStore;

        public MergeCartsService(IRepository<Visitor> visitors, IObjectStoreRepository objectStore)
        {
            this.visitors = visitors;
            this.objectStore = objectStore;
        }

        public ISystemMessage Handle(ISystemMessage request)
        {
            var mergeRequest = (MergeCartsRequest) request;
            var knownVisitors = visitors.FindById(mergeRequest.VisitorId);
            if(mergeRequest.AnonymousVisitorKey.Exists())
            {
                var anonymousVisitor = objectStore.Find((Guid)mergeRequest.AnonymousVisitorKey).Data as Visitor;
                knownVisitors.Cart.MergeWith(anonymousVisitor.Cart);
            }

            return new MergeCartsResponse();

        }
    }
}